package com.zhangxun.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zhangxun.constant.AllowLoginPath;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class LoginFilter implements GlobalFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //获取请求地址
        ServerHttpRequest request = exchange.getRequest();
        String value = request.getPath().value();
        //如果是登录地址，放行
        if(AllowLoginPath.ALLOW_PATH.contains(value)){
           return chain.filter(exchange);
        }

        //获取token，如果有token，并且和redis中的token相等，放行
        String token = request.getHeaders().getFirst("Authorization");
        if(StringUtils.hasText(token) && stringRedisTemplate.hasKey(token)){
          return  chain.filter(exchange);
        }

        //权限不满足，设置拦截，信息返回
        Map<String,Object> map = new HashMap<>();
        map.put("code", HttpStatus.UNAUTHORIZED.value());
        map.put("message","权限不足");
        map.put("success",false);
        ObjectMapper mapper = new ObjectMapper();
        byte[] bytes = {};
        try {
            bytes = mapper.writeValueAsBytes(map);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        ServerHttpResponse response = exchange.getResponse();

        DataBuffer data = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(data));
    }
}
